package com.dgshanger.sanhxiaofeisc.ui.home.utils

import android.app.Activity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.MotionEvent
import android.view.View
import com.dgshanger.sanhxiaofeisc.R
import com.dgshanger.sanhxiaofeisc.common.Constants
import java.lang.ref.WeakReference

/**
 * Created by JacobHHH on 2018/4/20.
 */
class ActivityCloseUtils private constructor(){

    private var mReference :WeakReference<Activity> ? = null
    private var mViewReference : WeakReference<Activity> ? = null

    companion object {

        private  var  mActivityCloseUtils : ActivityCloseUtils ?=null

        fun getInstance() : ActivityCloseUtils?{
            if (mActivityCloseUtils==null){
                synchronized(ActivityCloseUtils::class.java){
                    if (mActivityCloseUtils==null){
                        mActivityCloseUtils= ActivityCloseUtils()
                    }
                }
            }
            return mActivityCloseUtils
        }
    }

    fun finishActivity(activity : Activity, recycleView : RecyclerView) {
        mReference = WeakReference<Activity>(activity)

        recycleView.setOnTouchListener( object : View.OnTouchListener{
            private var startY=0.0f
            private var moveY =0.0f

            override fun onTouch(p0: View?, event : MotionEvent?): Boolean {

                when(event!!.action){
                    MotionEvent.ACTION_DOWN->{
                        startY=event.y
                    }
                    MotionEvent.ACTION_MOVE->{
                        moveY= startY-event.y
                    }
                    MotionEvent.ACTION_UP->{
                        Log.e("Tag","moveY="+moveY)
                        if (moveY<-300){
                            val lm = recycleView.layoutManager as LinearLayoutManager
                            val firstPosition = lm.findFirstVisibleItemPosition()
                            if (firstPosition==0&& lm.findViewByPosition(firstPosition).top==0){
                                activity.setResult(Constants.ACTIVITY_FINISH_RESULT_CODE)
                                activity.finish()
                                activity.overridePendingTransition(R.anim.translate_in,R.anim.translate_out)
                                return true
                            }
                        }
                    }
                }
                return false
            }

        })
    }



    fun detach(){
        if (mReference!=null){
            mReference!!.clear()
            mReference = null
        }
    }


}